package com.pucong.gitee.database.backup.business.service.util.fileService.pool;

import com.jcraft.jsch.*;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class SftpClientWapper {

    private static final int DEFAULT_BUFFER_SIZE = 4096;

    // 连接超时时间(3分钟未使用中断)
    public static final long CONN_TIMEOUT = 3 * 60 * 1000L;

    // 存放连接包装对象的池子的引用
    private LinkedBlockingQueue<SftpClientWapper> pool;

    private ChannelSftp channelSftp;

    private String host;

    ///激活时间（用于判断该连接是否长时间未使用）
    private long activeTime;

    private int port;

    private String username;

    private String password;

    private int clientTimeout;

    public SftpClientWapper(LinkedBlockingQueue<SftpClientWapper> pool, String host, int port, String username, String password) {
        this.pool = pool;
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.clientTimeout = 3000;
        this.activeTime = System.currentTimeMillis();
        this.makeObject();
    }

    public SftpClientWapper(LinkedBlockingQueue<SftpClientWapper> pool, String host, int port, String username, String password, int clientTimeout) {
        this.pool = pool;
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.clientTimeout = clientTimeout;
        this.activeTime = System.currentTimeMillis();
        this.makeObject();
    }

    private void makeObject() {
        Session session = null;
        Channel channel = null;
        try {
            Properties config = new Properties();
            // do not verify host key
            config.put("StrictHostKeyChecking", "no");
            //获取jsch的会话
            JSch jSch = new JSch();
            session = jSch.getSession(username, host, port);
            session.setConfig(config);
            //设置密码
            if (password != null && !"".equals(password)) {
                session.setPassword(password);
            }
            Properties sshConfig = new Properties();

            session.setConfig(sshConfig);
            session.setServerAliveInterval(92000);
            //连接  超时时间30s
            session.connect(clientTimeout);
            //开启sftp通道
            channel = session.openChannel("sftp");

            //通道连接 超时时间3s
            channel.connect(3000);
        } catch (Exception e) {
            log.error("SFTP服务器创建连接失败", e);
            throw new BusinessException("SFTP服务器创建连接失败");
        }
        this.channelSftp = (ChannelSftp) channel;
    }

    public ChannelSftp getSFtpChannel(){
        this.activeTime = System.currentTimeMillis();
        return channelSftp;
    }

    public void destroyObject() {
        if (channelSftp != null) {
            try {
                channelSftp.getSession().disconnect();
            } catch (JSchException e) {
                e.printStackTrace();
            }
            channelSftp.disconnect();
        }
    }

    public boolean validateObject() {
        return channelSftp.isConnected();
    }

    public void close() {
        log.info("-------------------------------------开始执行连接回收操作-------------------------------------");
        this.activeTime = System.currentTimeMillis();
        final boolean add = pool.add(this);
        log.info("-------------------------------------连接回收完毕-------------------------------------");
    }

    /**
     * 检测连接是否超时
     *
     * @return
     */
    public boolean checkTimeOut() {
        if ((System.currentTimeMillis() - this.activeTime) > SftpClientWapper.CONN_TIMEOUT) {
            return true;
        }
        return false;
    }
}
